#include "server.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

// char* get_full_path(const char* root_dir, const char* current_dir, const char* path) {
//     static char full_path[PATH_MAX];
//     char temp_path[PATH_MAX];
    
//     if (path[0] == '/') {
//         // 绝对路径
//         snprintf(temp_path, PATH_MAX, "%s%s", root_dir, path);
//     } else {
//         // 相对路径
//         snprintf(temp_path, PATH_MAX, "%s/%s/%s", root_dir, current_dir, path);
//     }
    
//     // 规范化路径
//     char* real_path = realpath(temp_path, NULL);
//     if (real_path == NULL) {
//         return NULL;
//     }
    
//     // 确保路径在用户根目录下
//     if (strncmp(real_path, root_dir, strlen(root_dir)) != 0) {
//         free(real_path);
//         return NULL;
//     }
    
//     snprintf(full_path, PATH_MAX, "%s", real_path);
//     free(real_path);
//     return full_path;
// }

char* get_full_path(const char* root_dir, const char* current_dir, const char* path) {
    static char full_path[PATH_MAX];
    snprintf(full_path, PATH_MAX, "%s/%s/%s", root_dir, current_dir, path);
    return full_path;
}

int handle_cd(ServerInfo* server, int client_index, const char* path) {
    ClientInfo* client = &server->clients[client_index];
    Message response;
    printf("%s, %s, %s\n", client->root_dir, client->current_dir, path);
    char* full_path = get_full_path(client->root_dir, client->current_dir, path);

    if (full_path == NULL) {
        response.type = MSG_TYPE_FAIL;
        response.length = snprintf(response.data, sizeof(response.data), "切换目录失败: 无效的路径");
    } else if (chdir(full_path) == 0) { // TODO 这里要改 ???
        // 更新客户端的当前目录
        char* relative_path = full_path + strlen(client->root_dir);
        if (relative_path[0] == '/') {
            relative_path++; // 跳过开头的 '/'
        }
        if (strlen(relative_path) == 0) {
            strcpy(client->current_dir, "/");
        } else {
            strncpy(client->current_dir, relative_path, PATH_MAX);
        }
        
        response.type = MSG_TYPE_SUCCESS;
        response.length = snprintf(response.data, sizeof(response.data), "%s", client->current_dir);
    } else {
        response.type = MSG_TYPE_FAIL;
        response.length = snprintf(response.data, sizeof(response.data), "切换目录失败: %s", path);
    }

    if (send_message(client->socket, &response) < 0) {
        perror("发送cd响应失败");
        return -1;
    }

    return 0;
}